package com.bjut.vendormgrsys.web.rest;

import com.bjut.vendormgrsys.constant.Constant.AuditStatus;
import com.bjut.vendormgrsys.constant.Constant.CampaignStatus;
import com.bjut.vendormgrsys.service.CampaignService;
import com.bjut.vendormgrsys.support.bo.UserBO;
import com.bjut.vendormgrsys.util.DateUtils;
import com.bjut.vendormgrsys.web.dto.*;
import com.bjut.vendormgrsys.web.dto.campaign.*;
import com.bjut.vendormgrsys.web.dto.user.Body;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
public class CampaignApiController implements CampaignApi{
    private final CampaignService campaignService;
    private final HttpServletRequest request;
    private static final Logger log = LoggerFactory.getLogger(UserApiController.class);

    @Autowired
    public CampaignApiController(CampaignService campaignService,HttpServletRequest request){
        this.campaignService = campaignService;
        this.request = request;
    }

    @Override
    public ResponseEntity<Success> campaignCreatePost(@Valid CampaignInfo body) {
        ResponseEntity<Success> successEntity;
        try{
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            UserBO creator = (UserBO) authentication.getPrincipal();

            String id = body.getId();
            if (!StringUtils.hasLength(id)) {
                body.setStatus(CampaignStatus.NEW.getKey());
                body.setAuditsStatus(AuditStatus.WAIT.getKey());
                body.setCreatorId(creator.getId());
                body.setDateCreated(DateUtils.now());
                body.setLastUpdated(null);
            } else {
                CampaignInfo campaignInfo = campaignService.findById(id, false);
                if(!campaignInfo.getCreatorId().equals(creator.getId())){
                    throw new Exception("非活动创建人不可编辑该活动");
                }
            }

            campaignService.saveCampaignPO(body);

            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.OK.value()).message("保存活动成功"), HttpStatus.OK);
        }catch (Exception e){
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("保存活动失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return successEntity;
    }

    @Override
    public ResponseEntity<ResultList> campaignFindAllPost(@Valid CampaignSearch body) {
        ResponseEntity<ResultList> successEntity;

        try{
            List<CampaignInfo> list = new ArrayList<>();
            long totalCount = campaignService.findAll(body, list);
            successEntity = new ResponseEntity<>(new ResultList().code(HttpStatus.OK.value()).message("成功").data(new ResultListData().totalCount(totalCount).items(list)), HttpStatus.OK);
            }catch (Exception e){
            successEntity = new ResponseEntity<>(new ResultList().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("获取用户列表失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }

        return successEntity;
    }

    @Override
    public ResponseEntity<Success> changeStatusPost(@Parameter(in = ParameterIn.DEFAULT, schema = @Schema()) @Valid @RequestBody List<Body> body) {
        ResponseEntity<Success> successEntity;
        try {
            campaignService.changeStatus(body);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.OK.value()).message("修改状态成功"), HttpStatus.OK);
        } catch (Exception e) {
            log.error("修改用户状态异常：", e);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("修改状态失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return successEntity;
    }

    @Override
    public ResponseEntity<Success> changeAuditStatusPost(@Parameter(in = ParameterIn.DEFAULT, schema = @Schema()) @Valid @RequestBody List<Body> body) {
        ResponseEntity<Success> successEntity;
        try {
            campaignService.changeAuditStatus(body);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.OK.value()).message("修改审核状态成功"), HttpStatus.OK);
        } catch (Exception e) {
            log.error("修改用户审核状态异常：", e);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("修改审核状态失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return successEntity;
    }

    @Override
    public ResponseEntity<ResultInfo> campaignInfoByIdPost(@RequestParam String id){
        ResponseEntity<ResultInfo> successEntity;
        CampaignInfo campaignInfo = campaignService.findById(id, true);
        successEntity = new ResponseEntity<>(new ResultInfo().code(HttpStatus.OK.value()).message("成功").data(campaignInfo), HttpStatus.OK);

        return successEntity;
    }

    @Override
    public ResponseEntity<ResultStatusList> statusListPost(@Valid CampaignSearch body) {
        ResponseEntity<ResultStatusList> responseEntity;
        try {
            List<Status> data = campaignService.findAllStatus(body);
            responseEntity = new ResponseEntity<>(new ResultStatusList().code(HttpStatus.OK.value()).message("成功").data(data), HttpStatus.OK);
        } catch (Exception e) {
            log.error("查询活动状态列表异常：", e);
            responseEntity = new ResponseEntity<>(new ResultStatusList().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("查询活动状态列表失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return responseEntity;
    }

    @Override
    public ResponseEntity<Success> signUpCampaignPost(@Valid List<CampaignUserInfo> body) {
        ResponseEntity<Success> successEntity;
        try {
            campaignService.signUpCampaignPost(body);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.OK.value()).message("报名成功"), HttpStatus.OK);
        } catch (Exception e) {
            log.error("报名异常：", e);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("报名失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return successEntity;
    }

    @Override
    public ResponseEntity<Success> cancelSignUpCampaignPost(@Valid List<CampaignUserInfo> body) {
        ResponseEntity<Success> successEntity;
        try {
            campaignService.cancelSignUpCampaignPost(body);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.OK.value()).message("取消报名成功"), HttpStatus.OK);
        } catch (Exception e) {
            log.error("取消报名异常：", e);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("取消报名失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return successEntity;
    }

    @Override
    public ResponseEntity<Success> addExpansionPost(@Valid CampaignUserInfo body) {
        ResponseEntity<Success> successEntity;
        try {
            campaignService.addExpansionPost(body);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.OK.value()).message("添加成功"), HttpStatus.OK);
        } catch (Exception e) {
            log.error("添加异常：", e);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("添加失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return successEntity;
    }

    @Override
    public ResponseEntity<Success> addExpansionFilePost(CampaignFile body) {
        ResponseEntity<Success> successEntity;
        try {
            if (body.getFile().isEmpty()) {
                throw new RuntimeException("文件不可为空！");
            }

            campaignService.addExpansionFilePost(body);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.OK.value()).message("添加成功"), HttpStatus.OK);
        } catch (Exception e) {
            log.error("添加异常：", e);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("添加失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return successEntity;
    }
}
